const crypto = require('crypto');
const axios = require('axios');

async function send(params){
    let serverUrl = 'http://smsapi.hexingtx.com/sms/batch/v1';

    let channelInfo = {
        appkey: params.account,
        appsecret: params.password,
        appcode: "1000"
    }
    let reqTs = new Date().getTime();


    let md5 = crypto.createHash('md5');
    let sign = md5.update(channelInfo.appkey + channelInfo.appsecret + reqTs).digest('hex');

    let reqData = {
        appkey : channelInfo.appkey,
        appcode : channelInfo.appcode,
        sign,
        phone : params.mobile,
        msg : params.content,
        timestamp : reqTs,
        extend : params.ext
    }
    let result = {}
    try{
        log.info('mt request to server:', JSON.stringify(reqData))
        let res = await axios.post(serverUrl, reqData);
        if(res.data.code === '00000'){
            result.status = 1;
            result.mt_msg_id = res.data.uid;
            result.report_status = 0;
        }else{
            result.status = 2;
            result.mt_msg_id = res.data.uid;
            result.report_status = 2;
            result.report_desc = res.data.code;
            result.report_time = new Date();
        }
        log.info('mt response from server:', res.data)
    }catch(err){
        log.error('mt server error:', err.message)
        console.log(err)
        result.status = 2;
        result.report_status = 2;
        result.report_desc = 'CHN_ERR'
        result.report_time = new Date();
    }finally {
        result.send_time = new Date();
        try{
            let r = await models.mtMsg.findByIdAndUpdate(params._id, {$set: result});
            //r = update success number
        }catch(e1){
            log.error('update submit resp err', e1.message)
        }
    }
}

module.exports = { send }
